package com.cloud.gateway.util;

import org.apache.commons.codec.binary.Base64;
import org.springframework.util.StringUtils;

import java.nio.ByteBuffer;

public class TokenUtil {

	public static String encode(String uid) {
		try {
			int size = uid.getBytes().length;
			if (size > 256) {
				return null;
			}
			ByteBuffer buf = ByteBuffer.allocate(size + 12);
			buf.putLong(System.currentTimeMillis());
			buf.putInt(size);
			buf.put(uid.getBytes());
			return Base64.encodeBase64URLSafeString(buf.array());
		} catch (Exception e) {
			return null;
		}
	}

	public static String decode(String token) {
		try {
			if (StringUtils.isEmpty(token)) {
				return null;
			}
			ByteBuffer buf = ByteBuffer.wrap(Base64.decodeBase64(token));
			buf.getLong();
			int size = buf.getInt();
			if (size > 256) {
				return null;
			}
			byte[] data = new byte[size];
			buf.get(data);
			return new String(data);
		} catch (Exception e) {
			return null;
		}
	}

}
